#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/11/6 09:57
# @Author  : supuchun
# @Site    :
# @File    : mns_demo.py

import sys
import time
from mns_python_sdk.mns.account import Account
from mns_python_sdk.mns.queue import *
from mns_python_sdk.mns.topic import *
from mns_python_sdk.mns.subscription import *
import ConfigParser
import base64
import json
from retrying import retry


class ali_mns:
    def __init__(self,send_queue,insert_queue):
        self.send_queue = send_queue
        self.insert_queue = insert_queue
        cfgFN = "./mns_python_sdk/sample.cfg"
        required_ops = [("Base", "AccessKeyId"), ("Base", "AccessKeySecret"), ("Base", "Endpoint")]
        optional_ops = [("Optional", "SecurityToken")]
        parser = ConfigParser.ConfigParser()
        parser.read(cfgFN)
        for sec,op in required_ops:
            if not parser.has_option(sec, op):
                sys.stderr.write("ERROR: need (%s, %s) in %s.\n" % (sec,op,cfgFN))
                sys.stderr.write("Read README to get help inforamtion.\n")
                sys.exit(1)
        accessKeyId = parser.get("Base", "AccessKeyId")
        accessKeySecret = parser.get("Base", "AccessKeySecret")
        endpoint = parser.get("Base", "Endpoint")
        securityToken = ""
        if parser.has_option("Optional", "SecurityToken") and parser.get("Optional", "SecurityToken") != "$SecurityToken":
            securityToken = parser.get("Optional", "SecurityToken")
        #初始化my_account
        global my_account
        my_account = Account(endpoint, accessKeyId, accessKeySecret, securityToken)

    @retry(stop_max_attempt_number = 5)
    def send_data(self,send_data):
        my_queue = my_account.get_queue(self.send_queue)
        # msg_body = '{"compare_id":"170186","company_id":205259,"task_id":250239,"img_url":"http:\/\/fwimage.cnfanews.com\/websiteimg\/2018\/20181029\/29029699\/40xkud0sxz4.jpg","assign_spider":1,"compare_type":0,"client_date":"2018-10-29 13:10:40","url":"https:\/\/www.dongqiudi.com\/article\/837911","clue_id":"342190","oss_url":"http:\/\/fwimage.cnfanews.com\/websiteimg\/2018\/20181029\/29029699\/40xkud0sxz4.jpg","is_cover":"0","surf_url":"http%3A%2F%2Felephant-spider.vpc100-oss-cn-beijing.aliyuncs.com%2Fhttp%3A%2F%2Ffwimage.cnfanews.com%2Fwebsiteimg%2F2018%2F20181029%2F29029699%2F40xkud0sxz4.jpg%3Fx-oss-process%3Dimage%2Fresize%2Cm_lfit%2Ch_400%2Cw_400"}'
        msg_body = send_data
        message = Message(msg_body)
        message.set_delayseconds(0)
        message.set_priority(10)
        try:
            send_msg = my_queue.send_message(message)
            sys.stdout.write("Send Message Succeed.\nMessageBody:%s\nMessageId:%s\nMessageBodyMd5:%s\n\n" % (msg_body, send_msg.message_id, send_msg.message_body_md5))
        except MNSExceptionBase, e:
            sys.stderr.write("Send Message Fail!\nException:%s\n\n" % e)
            sys.exit(1)

    @retry(stop_max_attempt_number=5)
    def get_message(self,send_queue):
        my_queue = my_account.get_queue(send_queue)
        try:
            wait_seconds = 10
            recv_msg = my_queue.receive_message(wait_seconds)
        except MNSExceptionBase, e:
            sys.stderr.write("Receive Message Fail!\nException:%s\n\n" % e)
            sys.exit(1)
        try:
            my_queue.delete_message(recv_msg.receipt_handle)
            #sys.stdout.write("Delete Message Succeed.\n\n")
        except MNSExceptionBase, e:
            #sys.stderr.write("Delete Message Fail!\nException:%s\n\n" % e)
            sys.exit(1)
        #aa = json.loads(recv_msg.message_body)
        return recv_msg.message_body



# while True:
#     a = ali_mns('elephant-test-one',"elephant-test-two")
#     ss = a.send_data()
# while True:
#     a = ali_mns('elephant-test-one', "elephant-test-two")
#     hh = a.get_message( "elephant-test-two")
#     print type(hh)
#     aaa = json.loads(hh,encoding="utf-8")
#     print aaa